package exhi.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;
import com.stp.rbac.entity.Dept;
import com.stp.rbac.entity.XRoot;
import com.stp.rbac.entity.XTree;
import com.stp.std.entity.FileAttach;
import com.stp.std.entity.ParamInfo;
import com.stp.std.entity.TreeInfo;
import com.stp.std.manager.TreeMng;

import exhi.entity.EntpCorp;
import exhi.entity.EntpRelation;
import exhi.entity.EntpUser;
import exhi.manager.EntpCorpMng;
import exhi.manager.EntpMng;

@Controller
@RequestMapping("/comm")
public class CommEntpAct extends BaseAct {

	// 参展企业
	@RequestMapping("/exhi-corp-detail")
	public void exhiCorpDetail(
			@ModelAttribute("entpCorp") EntpCorp corp,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "projectType", required = true, defaultValue = "") String projectType,
			ModelMap model) {
		model.addAttribute("projectId", projectId);
		model.addAttribute("projectType", projectType);
		model.addAttribute("corp", corp);

	}

	@RequestMapping("/exhi-corp-delete")
	@ResponseBody
	public String exhiCorpDelete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids) {
		delete("t_entp_corp", "id", ids);
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@RequestMapping("/exhi-corp-save")
	@ResponseBody
	public String exhiCorpSave(
			@ModelAttribute("entpCorp") EntpCorp corp,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "projectType", required = true, defaultValue = "") String projectType,
			ModelMap model) {
		corp.setProjectId(projectId);
		corp.setType(projectType);
		if (corp.getId() == null) {
			corp.setCreateTime(new Date());
			corpMng.save(corp);
		} else {
			corpMng.update(corp);
		}
		XMsg msg = new XMsg();
		return toJson(msg);
	}

	@RequestMapping("/exhi-corp")
	@ResponseBody
	public String commCorpList(
			XGridPage page,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "projectType", required = true, defaultValue = "") String projectType) {
		String sql = "from EntpCorp as info where 1=1 ";
		sql += sqlModel.getSQLChars("info.projectId", "=", projectId, false,
				"and");
		sql += sqlModel
				.getSQLChars("info.type", "=", projectType, false, "and");
		sql += " order by info.sort ";
		XGrid grid = null;
		if (projectType.equalsIgnoreCase("corp")) {
			CorpGridRow row = new CommEntpAct.CorpGridRow();
			grid = corpMng.getXGrid(sql, row, page.getPageNo(),
					page.getPageSize(), false);
		}
		if (projectType.equalsIgnoreCase("tw")) {
			TWGridRow row = new CommEntpAct.TWGridRow();
			grid = corpMng.getXGrid(sql, row, page.getPageNo(),
					page.getPageSize(), false);
		}

		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	@ModelAttribute("entpCorp")
	public EntpCorp getEntpCorp(
			@RequestParam(value = "corpId", required = true, defaultValue = "0") String id) {
		if ("".equalsIgnoreCase(id))
			id = "0";
		EntpCorp info = corpMng.get(new Integer(id));
		if (null == info) {
			info = new EntpCorp();
		}
		return info;
	}

	class CorpGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpCorp) {
				xrow = new XGridRow();
				EntpCorp info = (EntpCorp) obj;
				xrow.setId(info.getId().toString());
				List t = new ArrayList();
				t.add("");
				t.add(info.getEntpName());
				t.add(info.getContact());
				t.add(info.getTel());
				t.add("<a href='#' onclick=\"openWin('主要参展商','../comm/exhi-corp-detail.jspx?projectId="
						+ info.getProjectId()
						+ "&projectType=corp&corpId="
						+ info.getId().toString() + "',700,450);\">【编辑】</a>");
				xrow.setData(t);
			}
			return xrow;
		}
	}

	class TWGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpCorp) {
				xrow = new XGridRow();
				EntpCorp info = (EntpCorp) obj;
				xrow.setId(info.getId().toString());
				List t = new ArrayList();
				t.add("");
				t.add(info.getEntpName());
				t.add(info.getArea());
				t.add(info.getProduct());
				t.add("<a href='#' onclick=\"openWin('台资企业','../comm/exhi-corp-detail.jspx?projectId="
						+ info.getProjectId()
						+ "&projectType=tw&corpId="
						+ info.getId().toString() + "',700,450);\">【编辑】</a>");
				xrow.setData(t);
			}
			return xrow;
		}
	}

	// 查看附件
	@RequestMapping("/attach-view")
	public void viewFileAttach(
			@RequestParam(value = "aid", required = true, defaultValue = "") String aid,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String type,
			ModelMap model) {
		FileAttach attach = attachMng.find(aid, type);
		if (null == attach || attach.getPath().equalsIgnoreCase("")) {
			model.addAttribute("error", "暂无找到数据");
		} else {
			model.addAttribute("img", attach.getPath());
		}
	}

	// 多项选择展会分类
	@RequestMapping("/exhi-tree")
	public void commExhiTree(
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType,
			@RequestParam(value = "obj", required = true, defaultValue = "") String obj,
			ModelMap model) {
		model.addAttribute("projectId", projectId);
		model.addAttribute("entpType", entpType);
		model.addAttribute("obj", obj);
		String sql ="delete from t_entp_relation where projectId='"+ projectId + "' and entp_type='"+entpType+"'";
		relationMng.query(sql);
		sql = " from EntpRelation where 1=1 ";
		sql += sqlModel.getSQLChars("projectId", "=", projectId, false, "and");
		sql += sqlModel.getSQLChars("type", "=", entpType, false, "and");
		
		List<EntpRelation> lst=relationMng.list(sql);
		String chkIds="";
		for(EntpRelation r:lst){
			chkIds +=","+r.getEntpId();			
		}
		if (!chkIds.equalsIgnoreCase(""))
			model.addAttribute("chkIds", chkIds.substring(1));
		else
			model.addAttribute("chkIds", chkIds);
	}
	
	@RequestMapping("/exhi-tree-add")
	@ResponseBody
	public String exhiTreeAdd(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType) {
		String sql = "from TreeInfo as info where 1=1 ";
		sql += " and info.id in ('" + ids.replace(",", "','") + "')";
		List<TreeInfo> lst = treeMng.list(sql);
		EntpRelation relation;
		int i = 1;
		for (TreeInfo tree : lst) { 
			relation = new EntpRelation();
			relation.setEntpId(tree.getId());
			relation.setEntpName(tree.getTitle());
			relation.setType(entpType);
			relation.setProjectId(projectId);
			relation.setCreateTime(new Date());
			relation.setSort(i);
			sql = "delete from t_entp_relation  where projectId='" + projectId
					+ "' and entpId='" + tree.getId()+ "' and entp_type='"
					+ entpType + "'";
			relationMng.query(sql);
			relationMng.save(relation);
			i++;
		}
		return "";
	}

	@RequestMapping("/tree-tree")
	@ResponseBody
	public String tree(@RequestParam(value = "rootId", required = false) String rootId,@RequestParam(value = "chkIds", required = false) String chkIds) {
		XRoot root = new XRoot();
		root.addTree(getTree(rootId));
		if (chkIds.indexOf(",")>0){
			String[] aryStr=chkIds.split(",");
			for (int i=0;i<aryStr.length;i++){
				root.addCheckedId(aryStr[i]);
			}
		}else{
			root.addCheckedId(chkIds);
		}	
		return "{\"xTree\":" + toJson(root) + "}";
	}
	
	protected XTree getTree(String id) {
		List<TreeInfo> lst = treeMng.findByProperty("parentId", id, "sort");
		XTree t = new XTree();
		TreeInfo c;
		if (null == lst || lst.size() == 0) {
			c = treeMng.get(id);
			t.setId(c.getId());
			t.setText(c.getTitle());
			t.setChild("0");
			return t;
		} else {
			for (TreeInfo info : lst) {
				t.addTree(getTree(info.getId()));
			}
			c = treeMng.get(id);
			t.setId(c.getId());
			t.setText(c.getTitle());
			t.setChild("1");
			return t;
		}
	}
	
	// 多项选择展馆企业
	@RequestMapping("/addr-table")
	public void commExhiAddr(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType,
			@RequestParam(value = "obj", required = true, defaultValue = "") String obj,
			ModelMap model) {
		model.addAttribute("projectId", projectId);
		model.addAttribute("entpType", entpType);
		model.addAttribute("obj", obj);
		model.addAttribute("code", code);
	}
	
	
	@RequestMapping("/addr-detail")
	public void deptDetail(@ModelAttribute("dept") Dept dept,ModelMap model) {			
			List<ParamInfo> zones=paramMng.findByProperty("type","Zone");
			List<ParamInfo> deptTypes=paramMng.findByProperty("type","deptType");
			model.addAttribute("dept", dept);		
			model.addAttribute("zones", zones);			
			model.addAttribute("deptTypes", deptTypes);	
	}
	
	@RequestMapping("/addr-save")
	@ResponseBody
	public String deptSave(@ModelAttribute("dept") Dept dept) {
		if(dept.getId()==null){
			deptMng.save(dept);
		}else{
			deptMng.update(dept);
		}	
		XMsg msg = new XMsg();
		return toJson(msg);		
	}
	
	@ModelAttribute("dept")
	public Dept getDept(@RequestParam(value = "deptId", required = true, defaultValue = "") String id) {
		Dept info = deptMng.get(id);
		if (null == info) {
			info = new Dept();
		}
		return info;
	}
	
	//所有展馆企业
	@RequestMapping("/exhi-addr")
	@ResponseBody
	public String commExhiAddrList(XGridPage page,
			@RequestParam(value = "code") String code,
			@RequestParam("entp_name") String capName) {
		String sql = "from Dept as info where 1=1 ";
		sql += sqlModel.getSQLChars(" info.deptType", "=", "EX", false, "and");
		sql += sqlModel.getSQLChars(" info.deptStatus", "=", "T", false, "and");
		sql += sqlModel.getSQLChars(" info.deptName", "like", capName, false, "and");
		if ("B".equalsIgnoreCase(code))
			sql += sqlModel.getSQLChars(" info.deptCode", "<>","000000", false, "and");
		AddrGridRow row = new CommEntpAct.AddrGridRow();
		XGrid grid = relationMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}
	
	@RequestMapping("/exhi-addr-add")
	@ResponseBody
	public String exhiAddrAdd(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType) {
		String sql = "from Dept as info where 1=1 ";
		sql += " and info.id in ('" + ids.replace(",", "','") + "')";
		List<Dept> lst = deptMng.list(sql);
		EntpRelation relation;
		int i = 1;
		for (Dept dept : lst) { 
			relation = new EntpRelation();
			relation.setEntpId(dept.getId());
			relation.setEntpName(dept.getDeptName());
			relation.setType(entpType);
			relation.setProjectId(projectId);
			relation.setCreateTime(new Date());
			relation.setSort(i);
			sql = "delete from t_entp_relation  where projectId='" + projectId
					+ "' and entpId='" + dept.getId()+ "' and entp_type='"
					+ entpType + "'";
			relationMng.query(sql);
			relationMng.save(relation);
			i++;
		}
		return "";
	}
	

	// 多项选择企业信息
	@RequestMapping("/exhi-table")
	public void commExhiTable(
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType,
			@RequestParam(value = "obj", required = true, defaultValue = "") String obj,
			ModelMap model) {
		model.addAttribute("projectId", projectId);
		model.addAttribute("entpType", entpType);
		model.addAttribute("obj", obj);
	}

	@RequestMapping("/exhi-relation")
	@ResponseBody
	public String commRelationList(
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType) {
		String sql = " from EntpRelation where 1=1 ";
		// String sql =
		// "select e.uid,e.mc from t_entp_user as e inner join t_entp_relation r on e.uid=r.entpId  where 1=1 ";
		sql += sqlModel.getSQLChars("projectId", "=", projectId, false, "and");
		sql += sqlModel.getSQLChars("type", "=", entpType, false, "and");
		// sql += sqlModel.getSQLChars("e.zzjgdm", "=", capCode, false, "and");
		// sql += sqlModel.getSQLChars("e.mc", "like", capName, false, "and");
		RelationGridRow row = new CommEntpAct.RelationGridRow();
		XGrid grid = relationMng.getXGrid(sql, row, 0, 60, false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	@RequestMapping("/exhi-entp")
	@ResponseBody
	public String commExhiList(XGridPage page,
			@RequestParam("entp_code") String capCode,
			@RequestParam("entp_name") String capName) {
		String sql = "from EntpUser as info where 1=1 ";
		sql += sqlModel.getSQLChars("info.zzjgdm", "=", capCode, false, "and");
		sql += sqlModel.getSQLChars("info.mc", "like", capName, false, "and");
		EntpGridRow row = new CommEntpAct.EntpGridRow();
		XGrid grid = relationMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	@RequestMapping("/exhi-entp-add")
	@ResponseBody
	public String exhiEntpAdd(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType) {
		String sql = "from EntpUser as info where 1=1 ";
		sql += " and info.uid in ('" + ids.replace(",", "','") + "')";
		List<EntpUser> lst = entpMng.list(sql);
		EntpRelation relation;
		int i = 1;
		for (EntpUser entp : lst) {
			relation = new EntpRelation();
			relation.setEntpId(entp.getUid());
			relation.setEntpName(entp.getMc());
			relation.setType(entpType);
			relation.setProjectId(projectId);
			relation.setCreateTime(new Date());
			relation.setSort(i);
			sql = "delete from t_entp_relation  where projectId='" + projectId
					+ "' and entpId='" + entp.getUid() + "' and entp_type='"
					+ entpType + "'";
			relationMng.query(sql);
			relationMng.save(relation);
			i++;
		}
		return "";
	}

	@RequestMapping("/exhi-entp-delete")
	@ResponseBody
	public String exhiEntpDelete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids) {
		delete("t_entp_relation", "id", ids);
		return "";
	}

	@RequestMapping("/exhi-entp-list")
	@ResponseBody
	public String exhiEntpList(
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@RequestParam(value = "entpType", required = true, defaultValue = "") String entpType) {
		String s = getEntpRelaction(projectId, entpType);
		XMsg msg = new XMsg();
		msg.setMsg(s);
		return toJson(msg);
	}

	class RelationGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			/*
			 * if (obj instanceof Object[]) { xrow = new XGridRow(); Object[]
			 * object = (Object[]) obj; xrow.setId((String) object[0]); List t =
			 * new ArrayList(); t.add(""); t.add(object[1]); xrow.setData(t); }
			 */
			if (obj instanceof EntpRelation) {
				xrow = new XGridRow();
				EntpRelation object = (EntpRelation) obj;
				xrow.setId(object.getId().toString());
				List t = new ArrayList();
				t.add("");
				t.add(object.getEntpName());
				xrow.setData(t);
			}

			return xrow;
		}
	}

	class EntpGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpUser) {
				xrow = new XGridRow();
				EntpUser info = (EntpUser) obj;
				xrow.setId(info.getUid());
				List t = new ArrayList();
				t.add("");
				t.add(info.getMc());
				xrow.setData(t);
			}
			return xrow;
		}
	}
	
	class AddrGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof Dept) {
				xrow = new XGridRow();
				Dept info = (Dept) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				t.add("");
				t.add(info.getDeptName());
				t.add(paramMng.getVal(info.getQyCode(),"Zone"));
				t.add(deptMng.getDeptName(info.getQyCode(),"GS"));
				xrow.setData(t);
			}
			return xrow;
		}
	}

	@Autowired
	@Qualifier("entpMng")
	private EntpMng entpMng;

	@Autowired
	@Qualifier("entpCorpMng")
	private EntpCorpMng corpMng;
	
	@Autowired
	@Qualifier("treeMng")
	private TreeMng treeMng;

	
}
